package com.zn.realm;


import com.zn.pojo.User;
import com.zn.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;


public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    //角色授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取当前用户的信息
        Subject subject = SecurityUtils.getSubject();
        User user=(User)subject.getPrincipal();
        //添加角色
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRole(user.getRoles());
        //添加权限
        simpleAuthorizationInfo.addStringPermission(user.getPerms());
        return simpleAuthorizationInfo;
    }


    //用户的身份认证，就是拿到token后跟角色进行匹配
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //用页面输入的用户名和密码都分装到了authenticationToken。
        UsernamePasswordToken upt = (UsernamePasswordToken)authenticationToken;
        //从authenticationToken里面拿到用户名
        User user = userService.findByUserName(upt.getPrincipal().toString());
        if (user!=null){
            //将用户信息保存到AuthenticationInfo中
            return new SimpleAuthenticationInfo(user,user.getPassword(),getName());
        }
        return null;
    }
}
